package cn.zcy.controller.downloadandupload;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 基于servlet api文件下载
 */
@Controller
@RequestMapping("/user")
public class DownLoadController {
    @RequestMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.获取当前项目路径下的下载文件，（真实开发环境读取数据库或服务器）
        String path = request.getServletContext().getRealPath("/file/OverallBoothPlan.png");
        //2.根据文件路径分装成file对象
        File file = new File(path);

        //3.可以直接根据file对象获取文件名
        String fileName = file.getName();
        //4.设置响应头 content-disposition: 就是设置文件下载的打开方式，默认会在网页上打开
        //5.设置attachment:filename= 就是为了以下载的方式来打开文件
        //6.“UTF-8”设置如果文件有中文名就不会乱码
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //7.根据文件路径，分装成文件输入流
        InputStream in = new FileInputStream(path);
        int len = 0;
        //8.申明了一个1kb的字节的缓冲区
        byte[] bytes = new byte[1024];
        //9.获取输出流
        ServletOutputStream os = response.getOutputStream();
        //10.循环读取文件，每次读取1kb。避免内存溢出
        while ((len = in.read(bytes)) != -1) {
            //11.往客户端写入
            os.write(bytes, 0, len);
        }
        //12.关流
        in.close();
    }
}
